import React from 'react';
import { createModalContainer } from '@/components/changeModal';
import {Button, message, Form, Alert,Row, Col, List, Spin, InputNumber} from 'antd';
import { connect } from 'dva';
import styles from './index.less';
import {abs} from '@/utils/utils';


const FormItem = Form.Item;
@Form.create()
class ChangePriceComponent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            dataSource: [],
            FreightFee: 0,
            OrderItems: []
        }
    }

    componentWillMount() {
        this.findOrderItemFeeByOrderNo();
        window.Isoption = false;
    }

      componentDidMount() {
        window.Isoption = true;
      }

    // 取消
    handleCancel =() => {
        this.props.cancel();
    }

    findOrderItemFeeByOrderNo =() => {
        const { dispatch } = this.props;
        const data = [];
        dispatch({
            type: 'orderList/FindOrderItemFeeByOrderNo',
            payload: {
                OrderNo: `${this.props.param.OrderNo}`
            },
            callBack: {
                success: res => {
                    res.Data.OrderItems.forEach((item) => {
                        data.push({
                            OrderItemId: item.Id,
                            ProductFee: item.ModifyProductFee
                        })
                    })
                    this.setState({
                        dataSource: res.Data,
                        FreightFee: res.Data.FreightFee,
                        OrderItems: data
                    })
                },
                error: res => {
                    console.log(res.Msg)
                }
            }
        })
    }

    checkBlur = id => {
        this.props.form.validateFields([id], { force: true });
      };

      // 调价
      onInputChange =(value, id, index) => {
        const {OrderItems} = this.state;
        OrderItems[index]={
            OrderItemId: id,
            ProductFee: value?value/1:0
        };
        this.setState({
            OrderItems,
        })
      }

      // 输入运费
      changeFreightFee =value => {
          this.setState({
            FreightFee: value?value/1:0
          })
      }

      // 设置免运费
      clickFree =() => {
          this.props.form.setFieldsValue({
            freightFee: 0
          })
          this.setState({
            FreightFee: 0
          })
      }

      clickProductName=(Id)=> {
        window.open(`/#/${window.storeId}/goods/editproduct/${Id}`);
      }


      handleSubmit = e => {
        e.preventDefault();
        const { dispatch } = this.props;
        const { OrderItems } = this.state;
        this.props.form.validateFields((err, values) => {
            if(!err) {
                dispatch({
                    type: 'orderList/ModifiedFee',
                    payload: {
                        OrderNo: this.props.param.OrderNo,
                        FreightFee: values.freightFee,
                        OrderItems: OrderItems
                    },
                    callBack: {
                        success: res => {
                            if(res.Code ===0) {
                                message.success('修改成功'),
                                this.props.ok();
                            }
                        },
                        error: res => {
                            message.error(res.Msg)
                        }
                    }
                })
            }
        })
      }

    render() {
        const {dataSource, FreightFee, OrderItems} = this.state;
        const {getFieldDecorator} = this.props.form;
        const {loading1, loading2} = this.props;
        const  dataArr  = dataSource&&dataSource.OrderItems?dataSource.OrderItems:[];
        let add1 = 0; //小计
        if(dataArr.length> 0) {
            for(let i = 0; i< dataArr.length; i++) {
                add1 += dataArr[i].SubtotalFee
            }
        }
        let add2 = 0; // 输入调价的数
        if(OrderItems.length> 0) {
            for(let j = 0; j< OrderItems.length; j++) {
                add2 += OrderItems[j].ProductFee
            }
        }
        const lastPrace = (Number(add1) + Number(dataSource.DiscountFee) + Number(FreightFee/1) + Number(add2/1)).toFixed(2);  // 运算后价格
        return (
            <Form onSubmit={this.handleSubmit}>
                    <Spin spinning={loading1}>
                        <div className={styles.changepriceModal}>
                            <Alert message="只有订单未付款时才支持改价，改价后请联系买家刷新订单核实订单金额后再支付。" type="warning" showIcon />
                            <div className="xkd-mt16">
                                <Row className={styles.navRow} style={{marginBottom: 0}}>
                                    <Col span={4}>商品</Col>
                                    <Col span={3} className="xkd-text-r-padding">单价</Col>
                                    <Col span={2} className="xkd-text-r-padding">数量</Col>
                                    <Col span={3} className="xkd-text-right">小计</Col>
                                    <Col span={4} className="xkd-text-r-padding">涨价或减价</Col>
                                    <Col span={2} className="xkd-text-center">店铺优惠</Col>
                                    <Col span={3} className="xkd-text-right">运费</Col>
                                    <Col span={3} className="xkd-text-right">实付金额</Col>
                                </Row>
                                <Row style={{height: `${dataArr.length>0 ?dataArr.length * 80:80}px`}}>
                                    <Col span={16}>
                                        <List
                                            itemLayout="vertical"
                                            size="large"
                                            dataSource={dataSource&&dataSource.OrderItems?dataSource.OrderItems:[]}
                                            renderItem={(data, index) => {
                                                console.log(data.ModifyProductFee);
                                                return (
                                                    <List.Item>
                                                        <Row className={styles.list_item}>
                                                            <Col span={6} title={data.ProductName} className={styles.rowFirstItem}>
                                                            <a onClick={()=> this.clickProductName(data.ProductId)}>{data.ProductName}</a>
                                                            </Col>
                                                            <Col span={4} className="xkd-text-right">￥{abs(data.SingleFee,2)}</Col>
                                                            <Col span={3} className="xkd-text-right">{data.BuyNum}</Col>
                                                            <Col span={5} className="xkd-text-right">￥{abs(data.SubtotalFee,2)}</Col>
                                                            <Col span={6} className="xkd-text-r-padding">
                                                                <FormItem>
                                                                    {getFieldDecorator('input'+ data.Id,
                                                                        {initialValue: data.ModifyProductFee?data.ModifyProductFee:''}
                                                                    )(
                                                                        <InputNumber
                                                                            min={0-(data.SubtotalFee)/1}
                                                                            max={999999}
                                                                            onBlur={() => {
                                                                                this.checkBlur('input' + data.Id);
                                                                            }}
                                                                            onChange={(value)=> this.onInputChange(value, data.Id, index)}
                                                                        />
                                                                    )}
                                                                </FormItem>
                                                            </Col>
                                                        </Row>
                                                    </List.Item>
                                                )
                                            }}
                                        >
                                        </List>
                                    </Col>
                                    <Col span={2} className={`${styles.rbBorder} xkd-pt24`}>￥{abs(dataSource.DiscountFee,2)}</Col>
                                    <Col span={3} className={`${styles.rbBorder} xkd-pt16`}>
                                        <FormItem>
                                            {getFieldDecorator('freightFee',
                                                {initialValue: dataSource.FreightFee}
                                            )(
                                                <InputNumber onChange={this.changeFreightFee} min={0} max={9999}/>
                                            )}
                                        </FormItem>
                                        <div className={styles.freeText}><a onClick={this.clickFree}>直接免运费</a></div>
                                    </Col>
                                    <Col span={3} className={`${styles.nbBorder} xkd-text-right`}>￥{abs(lastPrace,2)}</Col>
                                </Row>
                                <div className={styles.footAddress}>
                                    <div>收货地址：{dataSource.Address}</div>
                                    <div>实付金额 = 小计 + 店铺优惠 +小计涨减价 +运费</div>
                                </div>
                            </div>
                        </div>
                    <FormItem className="xkd-model-footBtn">
                        <Button onClick={this.handleCancel} className="xkd-mr16">
                            取消
                        </Button>
                        <Button
                            type="primary"
                            htmlType="submit"
                            loading={loading2}
                        >
                            确认
                        </Button>
                    </FormItem>
                    </Spin>
            </Form>
        )
    }
}

const ChangePrice = createModalContainer(
    connect(({orderList, global, loading}) =>({
        orderList,
        loading1: loading.effects['orderList/FindOrderItemFeeByOrderNo'],
        loading2: loading.effects['orderList/ModifiedFee'],
    }))(ChangePriceComponent),
    true,
    true
);

export default ChangePrice;
